import urllib.request
from  lxml import etree

def create_request(page):
    if page==1:
        url= "https://sc.chinaz.com/tupian/gudianmeinvtupian.html"
    else:
        url="https://sc.chinaz.com/tupian/gudianmeinvtupian_" + str(page) + ".html"
    return url


def get_content(url):
    headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36"}
    request=urllib.request.Request(url=url,headers=headers)
    try:
        content = urllib.request.urlopen(request).read().decode('utf-8')
    except urllib.error.HTTPError as e:
        e.args = (url,) + e.args
        print(f'{url}的路径错误')
    except Exception as e:
        e.args = (url,) + e.args
    return content


def down_load(content):
   tree= etree.HTML(content)
   name_list=tree.xpath('//div[@class="tupian-list com-img-txt-list"]/div/img/@alt')
   url_list=tree.xpath('//div[@class="tupian-list com-img-txt-list"]/div/img/@data-original')
   for i in range (len(name_list)):
       url="https:"+url_list[i]
       try:
           urllib.request.urlretrieve(url, './images/' + name_list[i] + '.jpg')
       except Exception as e:
           e.args = (url,) + e.args




if __name__ == "__main__":
    start_page = int(input("请输入开始页:"))
    end_page = int(input("请输入结束页:"))
    for page in range(start_page,end_page+1):
        #请求对象的定制
        request=create_request(page)
        #获取源码
        content=get_content(request)

        #下载图片
        down_load(content)

